home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / var / lib / python-support / python2.6 / gdata / alt / appengine.pyc (.txt) < prev   
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  11.2 KB  |  288 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """Provides HTTP functions for gdata.service to use on Google App Engine
  5.  
  6. AppEngineHttpClient: Provides an HTTP request method which uses App Engine's
  7.    urlfetch API. Set the http_client member of a GDataService object to an
  8.    instance of an AppEngineHttpClient to allow the gdata library to run on
  9.    Google App Engine.
  10.  
  11. run_on_appengine: Function which will modify an existing GDataService object
  12.    to allow it to run on App Engine. It works by creating a new instance of
  13.    the AppEngineHttpClient and replacing the GDataService object's
  14.    http_client.
  15. """
  16. __author__ = 'api.jscudder (Jeff Scudder)'
  17. import StringIO
  18. import pickle
  19. import atom.http_interface as atom
  20. import atom.token_store as atom
  21. from google.appengine.api import urlfetch
  22. from google.appengine.ext import db
  23. from google.appengine.api import users
  24. from google.appengine.api import memcache
  25.  
  26. def run_on_appengine(gdata_service, store_tokens = True, single_user_mode = False):
  27.     """Modifies a GDataService object to allow it to run on App Engine.
  28.  
  29.   Args:
  30.     gdata_service: An instance of AtomService, GDataService, or any
  31.         of their subclasses which has an http_client member and a 
  32.         token_store member.
  33.     store_tokens: Boolean, defaults to True. If True, the gdata_service
  34.                   will attempt to add each token to it's token_store when
  35.                   SetClientLoginToken or SetAuthSubToken is called. If False
  36.                   the tokens will not automatically be added to the 
  37.                   token_store.
  38.     single_user_mode: Boolean, defaults to False. If True, the current_token
  39.                       member of gdata_service will be set when 
  40.                       SetClientLoginToken or SetAuthTubToken is called. If set
  41.                       to True, the current_token is set in the gdata_service
  42.                       and anyone who accesses the object will use the same 
  43.                       token. 
  44.                       
  45.                       Note: If store_tokens is set to False and 
  46.                       single_user_mode is set to False, all tokens will be 
  47.                       ignored, since the library assumes: the tokens should not
  48.                       be stored in the datastore and they should not be stored
  49.                       in the gdata_service object. This will make it 
  50.                       impossible to make requests which require authorization.
  51.   """
  52.     gdata_service.http_client = AppEngineHttpClient()
  53.     gdata_service.token_store = AppEngineTokenStore()
  54.     gdata_service.auto_store_tokens = store_tokens
  55.     gdata_service.auto_set_current_token = single_user_mode
  56.     return gdata_service
  57.  
  58.  
  59. class AppEngineHttpClient(atom.http_interface.GenericHttpClient):
  60.     
  61.     def __init__(self, headers = None):
  62.         self.debug = False
  63.         if not headers:
  64.             pass
  65.         self.headers = { }
  66.  
  67.     
  68.     def request(self, operation, url, data = None, headers = None):
  69.         """Performs an HTTP call to the server, supports GET, POST, PUT, and
  70.     DELETE.
  71.  
  72.     Usage example, perform and HTTP GET on http://www.google.com/:
  73.       import atom.http
  74.       client = atom.http.HttpClient()
  75.       http_response = client.request('GET', 'http://www.google.com/')
  76.  
  77.     Args:
  78.       operation: str The HTTP operation to be performed. This is usually one
  79.           of 'GET', 'POST', 'PUT', or 'DELETE'
  80.       data: filestream, list of parts, or other object which can be converted
  81.           to a string. Should be set to None when performing a GET or DELETE.
  82.           If data is a file-like object which can be read, this method will
  83.           read a chunk of 100K bytes at a time and send them.
  84.           If the data is a list of parts to be sent, each part will be
  85.           evaluated and sent.
  86.       url: The full URL to which the request should be sent. Can be a string
  87.           or atom.url.Url.
  88.       headers: dict of strings. HTTP headers which should be sent
  89.           in the request.
  90.     """
  91.         all_headers = self.headers.copy()
  92.         if headers:
  93.             all_headers.update(headers)
  94.         
  95.         data_str = data
  96.         if data:
  97.             if isinstance(data, list):
  98.                 converted_parts = [ _convert_data_part(x) for x in data ]
  99.                 data_str = ''.join(converted_parts)
  100.             else:
  101.                 data_str = _convert_data_part(data)
  102.         
  103.         if data and 'Content-Length' not in all_headers:
  104.             all_headers['Content-Length'] = str(len(data_str))
  105.         
  106.         if 'Content-Type' not in all_headers:
  107.             all_headers['Content-Type'] = 'application/atom+xml'
  108.         
  109.         if operation == 'GET':
  110.             method = urlfetch.GET
  111.         elif operation == 'POST':
  112.             method = urlfetch.POST
  113.         elif operation == 'PUT':
  114.             method = urlfetch.PUT
  115.         elif operation == 'DELETE':
  116.             method = urlfetch.DELETE
  117.         else:
  118.             method = None
  119.         return HttpResponse(urlfetch.Fetch(url = str(url), payload = data_str, method = method, headers = all_headers, follow_redirects = False))
  120.  
  121.  
  122.  
  123. def _convert_data_part(data):
  124.     if not data or isinstance(data, str):
  125.         return data
  126.     if hasattr(data, 'read'):
  127.         return data.read()
  128.     return str(data)
  129.  
  130.  
  131. class HttpResponse(object):
  132.     '''Translates a urlfetch resoinse to look like an hhtplib resoinse.
  133.  
  134.   Used to allow the resoinse from HttpRequest to be usable by gdata.service
  135.   methods.
  136.   '''
  137.     
  138.     def __init__(self, urlfetch_response):
  139.         self.body = StringIO.StringIO(urlfetch_response.content)
  140.         self.headers = urlfetch_response.headers
  141.         self.status = urlfetch_response.status_code
  142.         self.reason = ''
  143.  
  144.     
  145.     def read(self, length = None):
  146.         if not length:
  147.             return self.body.read()
  148.         return self.body.read(length)
  149.  
  150.     
  151.     def getheader(self, name):
  152.         if not self.headers.has_key(name):
  153.             return self.headers[name.lower()]
  154.         return self.headers[name]
  155.  
  156.  
  157.  
  158. class TokenCollection(db.Model):
  159.     '''Datastore Model which associates auth tokens with the current user.'''
  160.     user = db.UserProperty()
  161.     pickled_tokens = db.BlobProperty()
  162.  
  163.  
  164. class AppEngineTokenStore(atom.token_store.TokenStore):
  165.     """Stores the user's auth tokens in the App Engine datastore.
  166.  
  167.   Tokens are only written to the datastore if a user is signed in (if 
  168.   users.get_current_user() returns a user object).
  169.   """
  170.     
  171.     def __init__(self):
  172.         pass
  173.  
  174.     
  175.     def add_token(self, token):
  176.         '''Associates the token with the current user and stores it.
  177.     
  178.     If there is no current user, the token will not be stored.
  179.  
  180.     Returns:
  181.       False if the token was not stored. 
  182.     '''
  183.         tokens = load_auth_tokens()
  184.         if not hasattr(token, 'scopes') or not (token.scopes):
  185.             return False
  186.         for scope in token.scopes:
  187.             tokens[str(scope)] = token
  188.         
  189.         key = save_auth_tokens(tokens)
  190.         if key:
  191.             return True
  192.         return False
  193.  
  194.     
  195.     def find_token(self, url):
  196.         """Searches the current user's collection of token for a token which can
  197.     be used for a request to the url.
  198.  
  199.     Returns:
  200.       The stored token which belongs to the current user and is valid for the
  201.       desired URL. If there is no current user, or there is no valid user 
  202.       token in the datastore, a atom.http_interface.GenericToken is returned.
  203.     """
  204.         if url is None:
  205.             return None
  206.         if isinstance(url, (str, unicode)):
  207.             url = atom.url.parse_url(url)
  208.         
  209.         tokens = load_auth_tokens()
  210.         if url in tokens:
  211.             token = tokens[url]
  212.             if token.valid_for_scope(url):
  213.                 return token
  214.             del tokens[url]
  215.             save_auth_tokens(tokens)
  216.         
  217.         for scope, token in tokens.iteritems():
  218.             if token.valid_for_scope(url):
  219.                 return token
  220.         
  221.         return atom.http_interface.GenericToken()
  222.  
  223.     
  224.     def remove_token(self, token):
  225.         """Removes the token from the current user's collection in the datastore.
  226.     
  227.     Returns:
  228.       False if the token was not removed, this could be because the token was
  229.       not in the datastore, or because there is no current user.
  230.     """
  231.         token_found = False
  232.         scopes_to_delete = []
  233.         tokens = load_auth_tokens()
  234.         for scope, stored_token in tokens.iteritems():
  235.             if stored_token == token:
  236.                 scopes_to_delete.append(scope)
  237.                 token_found = True
  238.                 continue
  239.         
  240.         for scope in scopes_to_delete:
  241.             del tokens[scope]
  242.         
  243.         if token_found:
  244.             save_auth_tokens(tokens)
  245.         
  246.         return token_found
  247.  
  248.     
  249.     def remove_all_tokens(self):
  250.         """Removes all of the current user's tokens from the datastore."""
  251.         save_auth_tokens({ })
  252.  
  253.  
  254.  
  255. def save_auth_tokens(token_dict):
  256.     """Associates the tokens with the current user and writes to the datastore.
  257.   
  258.   If there us no current user, the tokens are not written and this function
  259.   returns None.
  260.  
  261.   Returns:
  262.     The key of the datastore entity containing the user's tokens, or None if
  263.     there was no current user.
  264.   """
  265.     if users.get_current_user() is None:
  266.         return None
  267.     user_tokens = TokenCollection.all().filter('user =', users.get_current_user()).get()
  268.     if user_tokens:
  269.         user_tokens.pickled_tokens = pickle.dumps(token_dict)
  270.         return user_tokens.put()
  271.     user_tokens = TokenCollection(user = users.get_current_user(), pickled_tokens = pickle.dumps(token_dict))
  272.     return user_tokens.put()
  273.  
  274.  
  275. def load_auth_tokens():
  276.     """Reads a dictionary of the current user's tokens from the datastore.
  277.   
  278.   If there is no current user (a user is not signed in to the app) or the user
  279.   does not have any tokens, an empty dictionary is returned.
  280.   """
  281.     if users.get_current_user() is None:
  282.         return { }
  283.     user_tokens = TokenCollection.all().filter('user =', users.get_current_user()).get()
  284.     if user_tokens:
  285.         return pickle.loads(user_tokens.pickled_tokens)
  286.     return { }
  287.  
  288.